<?php


namespace app\admin\controller;


use app\common\model\AdminActionLog;
use app\common\traits\Jump;
use ke\auth\logic\Auth;
use think\App;
use think\Container;
use think\exception\ValidateException;
use think\Request;

/**
 * Class BaseController
 * @package app\admin\controller
 * @property-read Auth $auth
 */
abstract class BaseController
{
    use Jump;


    /**
     * @var App
     */
    protected $app;


    /**
     * @var Request
     */
    protected $request;


    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];


    public function __construct()
    {
        $this->app = Container::get('app');
        $this->request = $this->app->request;
        $this->registerMiddleware();
        $this->init();
    }


    protected function init()
    {}


    public function __get($name)
    {
        if ($name === 'auth') {
            return Auth::instance();
        }
    }


    /**
     * 注册控制器中间件
     */
    private function registerMiddleware()
    {
        foreach ($this->middleware as $key => $val) {
            if (!is_int($key)) {
                $only = $except = null;

                if (isset($val['only'])) {
                    $only = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['only']);
                } elseif (isset($val['except'])) {
                    $except = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['except']);
                }

                if (isset($only) && !in_array($this->request->action(), $only)) {
                    continue;
                } elseif (isset($except) && in_array($this->request->action(), $except)) {
                    continue;
                } else {
                    $val = $key;
                }
            }

            $this->app['middleware']->controller($val);
        }
    }


    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param null $scene 场景
     * @param bool $batch 是否批量验证
     * @param mixed $callback 回调方法（闭包）
     * @return true
     */
    protected function validate($data, $validate, $scene = null, $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = $this->app->validate();
            $v->rule($validate);
        } else {
            $v = $this->app->validate($validate);
        }
        if (!is_null($scene)) {
            $v->scene($scene);
        }

        // 是否批量验证
        if ($batch) {
            $v->batch(true);
        }

        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            throw new ValidateException($v->getError());
        }

        return true;
    }


    /**
     * 记录操作日志
     * @param string $message 日志内容
     * @return AdminActionLog
     */
    protected function recordActionLog($message)
    {
        $data = [
            'admin_id'=>$this->auth->id,
            'controller'=>$this->request->controller()
                . '@' . $this->request->action(),
            'message'=>$message,
            'ip'=>$this->request->ip(true),
            'agent'=>$this->request->header('user-agent'),
        ];

        $find = AdminActionLog::where('is_deleted', 1)->find();
        if (!$find) {
            $find = new AdminActionLog();
        } else {
            $find->is_deleted = 0;
            $find->create_time = $_SERVER['REQUEST_TIME'];
        }
        $find->save($data);
        return $find;
    }

}
